package com.ycsj.goldmedalnewconcept.fragment;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import com.ycsj.goldmedalnewconcept.activity.ClassThirdActivity;
import com.ycsj.goldmedalnewconcept.activity.LoginActivity;
import com.ycsj.goldmedalnewconcept.bean.ClassSecondListInfo;
import com.ycsj.goldmedalnewconcept.bean.ClassSecondResp;
import com.ycsj.goldmedalnewconcept.bean.WordSecondResq2;
import com.ycsj.goldmedalnewconcept.bean.mineBasicInfoResp2;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.view.RoundedTransformationBuilder;
import com.ycsj.goldmedalnewconcept.R;

/**
 * 微课堂二级菜单 首页fragment ViewPager tab
 * 
 * @author dewyze
 */
public class ClassSecondFragment extends BaseFragment {

	private static final String TAG = "ClassSecondFragment";
	private Activity mActivity;
	private TextView mMsgTv;
	private String mMsgName;
	private TextView tv_title;
	private RelativeLayout mProgressBar;

	public void setMsgName(String msgName) {
		this.mMsgName = msgName;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mActivity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_grammar_second,
				container, false);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initViews(view);

		SPUtils.put(getActivity(), ConfigConstant.CURRENTFRAGMENT, TAG);
		int GRADE_ID = getArguments().getInt("GRADE_ID");
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		//http://m.moregolden.com:8080/ycsj_platform/ycsj_platform.aspx 

		final Request request = new Request.Builder().url(
				NetConstant.ycsj_platform+ "?type=1&gradeid="+GRADE_ID+
    			"&account="+SPUtils.getString(getActivity(), ConfigConstant.USERNAME)+
    			"&role="+SPUtil.getString(getActivity(), "role","0")).build();
//		final Request request = new Request.Builder().url(
//				NetConstant.CLASSTEST
//				+ "/GradeInfo.aspx?gradeid="
//				+ GRADE_ID
//				+ "&account="
//				+ SPUtils.getString(getActivity(),
//						ConfigConstant.USERNAME)
//						+ "&usertoken="
//						+ SPUtils.getString(getActivity(),
//								ConfigConstant.USERTOKEN)).build();
		// new call
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBack);

		// int GRADE_ID =Integer.parseInt(getArguments().getString("GRADE_ID"));
		// +SPUtils.getString(getActivity(),
		// ConfigConstant.USERNAME)+"&usertoken="
		// +SPUtils.getString(getActivity(), ConfigConstant.USERTOKEN) ,
		// callBack);
		// int GRADE_ID =getArguments().getInt("GRADE_ID");
		//
		// Log.e("test",
		// NetConstant.CLASSTEST+"/GradeInfo.aspx?gradeid="+GRADE_ID+"&account=15098012693&usertoken=502337d5-52ec-416d-ac6b-181a79a95461");
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initDisplay();
	}

	private void initViews(View view) {

		mProgressBar = (RelativeLayout) view.findViewById(R.id.progressBar);

		tv_title = (TextView) view.findViewById(R.id.tv_title);
		TextView tv_back = (TextView) view.findViewById(R.id.tv_back);
		String GRADE_NAME = getArguments().getString("GRADE_NAME");
		tv_title.setText(GRADE_NAME);
		tv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				HomeFragment gf = new HomeFragment();
				ft.replace(R.id.center_layout, gf);
				ft.addToBackStack(null);
				ft.commit();
			}
		});

		lv_grammar = (ListView) view.findViewById(R.id.lv_grammar);
		lv_grammar.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				if (!SPUtils.getBoolean(getActivity(),
//						ConfigConstant.IS_LOGIN_ON)) {
//					// getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_fragment_container,
//					// new NotLoggedFragment()).commit();
//					Intent intent = new Intent(getActivity(),
//							LoginActivity.class);
//					startActivity(intent);
//				} else {

					Intent intent = new Intent(getActivity(),
							ClassThirdActivity.class);
					intent.putExtra("lESSON_ID", list.get(position).LESSON_ID);
					intent.putExtra("LESSON_NAME",
							list.get(position).LESSON_NAME);
					startActivity(intent);
//				}

			}
		});
	}

	private void initDisplay() {
		// mMsgTv.setText(mMsgName + "");

		// iv_home01.setOnTouchListener(onTouch);

	}

	@Override
	public String getFragmentName() {
		return TAG;
	}

	public OnTouchListener onTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_UP:

				Animation shakeAnim = AnimationUtils.loadAnimation(
						getActivity(), R.anim.shake);
				v.startAnimation(shakeAnim);

				break;
			}
			return true;
		}

	};

	public Animation shakeAnimation(int CycleTimes) {
		Animation translateAnimation = new TranslateAnimation(0, 0, -10, 10);
		translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

	class MyAdapter extends BaseAdapter {
		private ArrayList<ClassSecondListInfo> list;

		public MyAdapter(ArrayList<ClassSecondListInfo> list2) {
			super();
			this.list = list2;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		ViewHolder vh = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = View.inflate(parent.getContext(),
						R.layout.items_grammar_lv, null);
				vh = new ViewHolder();
				vh.tv_grammar_unit = (TextView) convertView
						.findViewById(R.id.tv_grammar_unit);
				vh.iv_grammar_second_bg = (ImageView) convertView
						.findViewById(R.id.iv_grammar_second_bg);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			vh.tv_grammar_unit.setText(list.get(position).LESSON_NAME);

			Transformation transformation = new RoundedTransformationBuilder()
					.cornerRadiusDp(10).build();

			if (position % 2 == 0) {

				Picasso.with(getActivity()).load(R.drawable.grammer_cover1)
						.fit().transform(transformation)
						.into(vh.iv_grammar_second_bg);
			} else {
				Picasso.with(getActivity()).load(R.drawable.grammer_cover2)
						.fit().transform(transformation)
						.into(vh.iv_grammar_second_bg);
			}

			return convertView;
		}

		class ViewHolder {
			private TextView tv_grammar_unit;
			private ImageView iv_grammar_second_bg;
		}
	}

	private ArrayList<ClassSecondListInfo> list;
	Handler handler = new Handler();

	Callback callBack = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {

			String json = arg0.body().string();
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			 Log.e("test", json);

			Gson gson = new Gson();
			// // 2 使用gson对象的方法
			if ("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)
					|| "2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)
					|| "没查询到用户基本信息".equals(gson.fromJson(json,
							WordSecondResq2.class).RESULTTYPE)) {
				// getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_fragment_container,
				// new NotLoggedFragment()).commit();
				// Intent intent = new
				// Intent(getActivity(),NotLoggedActivity.class);
				// startActivity(intent);
			} else {
				ClassSecondResp classSecondResp = gson.fromJson(json,
						ClassSecondResp.class);
				list = classSecondResp.LIST;
				// Log.i("test", ""+list.size());
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						mProgressBar.setVisibility(mProgressBar.GONE);
						lv_grammar.setAdapter(new MyAdapter(list));
						
					}
				}, 10);

			}
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};
	private ListView lv_grammar;

}
